<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex;flex-direction: row;">
      <el-form ref="form" :model="form" label-width="100px" label-position="left" :inline="true">
        <el-form-item label="应用类型:" prop="iApptype">
          <el-select v-model="form.iApptype" placeholder="请选择应用类型" clearable class="filter-item">
            <el-option
              v-for="item in orgList"
              :key="item.iAppnum"
              :label="item.strValue"
              :value="item.strCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用名称:" prop="strAppname">
          <el-input v-model="form.strAppname" placeholder="请输入应用名称" class="filter-item" />
        </el-form-item>
        <el-form-item label="起始日期:" prop="value">
          <el-date-picker
            v-model="value"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          style="margin-left: 12px;"
          @click="handleSearch()"
        >搜索</el-button>
        <el-button class="filter-item" @click="$refs['form'].resetFields()">重置</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="addEquipment">新增应用</el-button>
        <!--<el-button class="filter-item" type="danger" @click="deleteFileOrDirectory(numArr)"
                   :disabled="this.numArr.length === 0">批量删除
        </el-button>-->
      </el-form>
    </div>
    <!--@selection-change="selsChange"-->
    <el-table :data="listData" style="width: 100%" border @selection-change="selsChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        prop="id"
        :index="indexMethod"
        align="center"
        label="序号"
        width="55"
      />
      <el-table-column prop="strAppname" align="center" label="应用名称" />
      <el-table-column prop="strCover" align="center" label="应用封面" width="120">
        <template slot-scope="{row}">
          <el-image
            style="width: 65px; height: 65px;border-radius: 5px"
            :src="row.strCover"
            :preview-src-list="[row.strCover]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="strPackagename" align="center" label="应用包名/链接" width="180">
        <template slot-scope="scope">{{ scope.row.strPackagename?scope.row.strPackagename:'/' }}</template>
      </el-table-column>
      <el-table-column prop="iApptypename" align="center" label="应用类型" />
      <!--<el-table-column prop="iApptypename" align="center" label="设备类型" width="190"/>-->
      <el-table-column prop="strCreatetime" align="center" label="创建时间" />
      <el-table-column prop="strOperatorname" align="center" label="创建者" />
      <el-table-column align="center" label="操作" width="255">
        <template slot-scope="{row,$index}">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button size="mini" type="primary" @click="handelEdit(row,$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
            <el-button
              size="mini"
              type="success"
              @click="ShowDetail(row,$index),dialogTableVisible = true"
            >详情</el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="success"
              @click="ShowDetail(row,$index),dialogTableVisible = true"
            >详情</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="form.pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="fetchList(form)"
    />
    <!--添加弹窗-->
    <el-dialog
      title="应用详情"
      width="70%"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      top="10vh"
    >
      <template>
        <!--查看应用详情-->
        <h3>基本信息</h3>
        <el-table :data="gridData" border>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" prop="id" align="center" label="序号" width="55" />
          <el-table-column prop="strAppname" align="center" label="应用名称" width="160" />
          <el-table-column prop="strCover" align="center" label="应用封面" width="160">
            <template slot-scope="{row}">
              <el-image
                style="width: 65px;height: 55px;border-radius: 10px"
                :src="row.strCover"
                :preview-src-list="[row.strCover]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="strDetail" align="center" label="应用描述" width="160" />
          <el-table-column prop="strPackagename" align="center" label="应用包名/链接" width="160" />
          <el-table-column prop="iApptypename" align="center" label="应用类型" width="160" />
          <el-table-column prop="strCreatetime" align="center" label="创建时间" width="160" />
          <el-table-column prop="strCreatetime" align="center" label="创建者" width="160">
            <template>admin</template>
          </el-table-column>
        </el-table>

        <el-row :gutter="10" type="flex" align="middle">
          <el-col :span="6">
            <h3>应用数据</h3>
          </el-col>
        </el-row>
        <el-table ref="multipleTable" :data="gridDatas" border max-height="250">
          <el-table-column type="index" prop="ID" label="序号" align="center" width="55" />
          <el-table-column prop="iOrgsysnum" label="机构编号" align="center" />
          <el-table-column prop="strOrgname" label="机构名称" align="center" />
          <el-table-column prop="orgLevelname" label="级别" align="center" />
          <el-table-column prop="superOrgInfo" label="上级机构" align="center" />
          <el-table-column prop="childOrgInfo" label="下级机构" align="center" />
          <el-table-column prop="num" label="设备数" align="center" />
        </el-table>
        <template v-if="isVisible">
          <el-row :gutter="10" type="flex" align="middle">
            <el-col :span="6">
              <h3>素材信息</h3>
            </el-col>
            <el-col :span="6" :push="12" style="text-align:right">
              <el-button size="mini" type="primary" @click="handleSource">素材来源</el-button>
            </el-col>
          </el-row>
          <el-table ref="multipleTable" :data="materialDatas" max-height="240" border>
            <el-table-column type="index" prop="ID" label="序号" align="center" width="55" />
            <el-table-column prop="I_ORGSYSNUM" label="机构编号" align="center" />
            <el-table-column prop="STR_MATERIALNAME" label="素材名称" align="center" />
            <el-table-column prop="STR_MATERIALENCODE" label="素材包名" align="center" />
            <el-table-column prop="STR_DOWNLOAD" label="下载地址" align="center">
              <template slot-scope="{row}">
                <a :href="row.STR_DOWNLOAD" target="_blank" class="link-type">预览</a>
              </template>
            </el-table-column>
            <el-table-column prop="STR_CREATETIME" label="创建时间" align="center" />
            <!-- <el-table-column prop="num" label="设备数" align="center" /> -->
          </el-table>
        </template>
      </template>
    </el-dialog>
    <!--新增应用页面表单-->
    <el-dialog
      :title="titleMap[dialogStatus]"
      :buttonadd="buttonadd"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="应用名称" prop="strAppname">
          <el-input v-model="ruleForm.strAppname" />
        </el-form-item>

        <el-form-item label="应用类型" prop="iApptype">
          <el-select v-model="ruleForm.iApptype" placeholder="请选择应用类型" @change="clearinput">
            <el-option v-for="item in orgList" :key="item.iAppnum" :label="item.strValue" :value="item.strCode" />
          </el-select>
        </el-form-item>
        <!-- item.strCode > 0 -->
        <el-form-item v-if="ruleForm.iApptype === '2'" label="应用包名" prop="strPackagename">
          <el-input v-model="ruleForm.strPackagename" placeholder="请填写应用包名(例:com.jdk.com)" />
        </el-form-item>
        <el-form-item v-if="ruleForm.iApptype === '3'" label="链接地址" prop="strPackagename">
          <el-input v-model="ruleForm.strPackagename" placeholder="请填写链接" />
        </el-form-item>
        <el-form-item label="应用描述" prop="strDetail">
          <el-input v-model="ruleForm.strDetail" type="textarea" />
        </el-form-item>
        <el-form-item label="应用图标" prop="strCover">
          <el-upload
            class="avatar-uploader"
            :action="baseImgRUL"
            name="uploadFile"
            :show-file-list="false"
            :on-success="(response, file)=>handleSuccess(response, file, 'ruleForm', 'strCover','strCoversize')"
            :on-remove="handleRemove"
            :on-change="handleSuccesslh"
            :before-upload="beforeUpload"
          >
            <img v-if="ruleForm.strCover" :src="ruleForm.strCover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item v-if="buttonadd==1" label="发布范围" prop="strOrgnum">
          <el-cascader
            v-if="iOrgnum===-1"
            v-model="strOrgnum"
            :show-all-levels="false"
            :options="options"
            placeholder="总行"
            :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            @change="handleChange"
          />
          <el-cascader
            v-else
            v-model="strOrgnum"
            :show-all-levels="false"
            :options="optionslist"
            placeholder="总行"
            :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item v-if="buttonadd==2" label="发布范围">
          <el-table :data="changefbDatas" border>
            <el-table-column prop="strOrgname" label="机构名称" align="center" />
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
        <el-button @click="dialogFormVisible = false">取 消</el-button>

        <el-button v-if="buttonadd===1" type="primary" @click="submitForm('ruleForm')">新 增</el-button>
        <el-button v-else type="primary" @click="changeFormbtn('ruleForm')">修 改</el-button>
      </div>
    </el-dialog>
    <marar-dialog-com v-if="visible" :visible="visible" :i-appnum-tomat="iAppnumTomat" :from-parent-data="materialDatas" />
  </div>
</template>

<script>
import {
  getdeploymentList,
  getselectList,
  addInfo,
  deleteInfo,
  detailTable,
  detailrelevance,
  getOrglist,
  getOrglists,
  updateAppInfo,
  deleteAllInfo,
  fetchMaByApplist
} from '@/api/codeapi'
import Pagination from '@/components/Pagination'
import mixins from '@/mixins/uploadImg'
import MararDialogCom from './component/matarDialogCom'
import { mapGetters } from 'vuex'
// import { addMaterial } from '../../../api/addTag'

export default {
  components: { Pagination, MararDialogCom },
  mixins: [mixins],
  data() {
    var checkstrPackagename = (rule, value, callback) => {
      const strRegex = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/
      if (this.ruleForm.iApptype === '2') {
        if (value === '') {
          callback(new Error('请输入应用包名称,例:com.jdk.com'))
        } else {
          callback()
        }
      } else if (value === '') {
        callback(new Error('请输入应用链接'))
      } else if (!strRegex.test(value)) {
        callback(new Error('地址必须以http/https/ftp/ftps开头'))
      } else {
        callback()
      }
    }
    var checkstrAppname = (rule, value, callback) => {
      const nameRegex = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
      if (value === '') {
        callback(new Error('请输入应用名称'))
      } else if (!nameRegex.test(value)) {
        callback(new Error('请不要输入特殊符号'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        strAppname: [
          { required: true, validator: checkstrAppname, trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        iApptype: [
          { required: true, message: '请选择应用类型', trigger: 'blur' }
        ],
        strPackagename: [
          { required: true, validator: checkstrPackagename, trigger: 'blur' }
        ],
        strDetail: [
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur'
          }
        ],
        /* strOrgnum: [
              { required: true, message: '请选择发布范围', trigger: 'change' }
            ],*/
        strCover: [{ required: true, message: '请上传图片', trigger: 'change' }]
      },
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper',

      imageUrl: '',
      mixUploadUrl: '',
      tableKey: 0, // 暂无用到
      listLoading: true, // 暂无用到
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      visible: false,
      buttonadd: 1,
      value: '',
      orgList: [],
      listData: [],
      gridData: [],
      gridDatas: [],
      changefbDatas: [],
      optionsType: [],
      options: [], // 所属机构
      optionslist: [], // 所属机构有权限

      dialogStatus: '',

      isVisible: false, // 是否显示素材来源

      // 新增弹窗内容
      dialogTableVisible: false, // 新增的表格
      dialogFormVisible: false, // 新增的form
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        addEquipment: '新增应用',
        editEquipment: '修改应用'
      },
      // 搜索表单
      form: {
        iApptype: '',
        strAppname: '',
        startTime: '',
        endTime: '',
        pagenum: 1,
        userOrg: this.$store.getters.iOrgsysnum
      },

      // 新增应用页面表单
      ruleForm: {
        iApptype: '',
        strAppname: '',
        strCover: '',
        strPackagename: '',
        strDetail: '',
        iStatus: '',
        id: '',
        iAppnum: '',
        deviceType: 1,
        strOrgnum: '',
        valArr: [],
        strOperator: this.$store.getters.userID,
        strCoversize: ''  //应用图片大小
      },
      strOrgnum: [],
      numArr: [],
      iOrgnum: this.$store.getters.iOrgsysnum,
      materialDatas: [],
      iAppnumTomat: ''
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum', 'userID'])
  },
  // 页面打开加载
  created() {
    this.fetchList()
    this.getOrglistsq()
  },
  // 接口数据
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList)
    },
    fetchList() {
      // this.userOrg = this.$store.getters.iOrgsysnum   //获取登录账号所属的机构编号,this.$store.getters[组件/变量]
      // this.userOrgtype = this.$store.getters.iUsertype

      // 获取应用部署列表数据
      getdeploymentList(this.form)
        .then(res => {
          this.listData = res && res.pages
          this.total = !res ? 0 : res.total
          this.currentpage = res.currentpage
        })
        .catch(err => {
          console.log(err)
        })
      // 获取应用类型数据select
      getselectList({ typeInfo: [5] }).then(res => {
        /* this.orgList = res.syslist[5]*/ // 没有加code码之前
        this.orgList = res.data[5].filter(item => item.strCode > 0)
      })
      // 获取所属机构
      getOrglist().then(res => {
        // console.log(res)
        /* this.options = res.yhlist*/
        this.options = res.data
      })
    },
    // 获取所属机构有权限
    getOrglistsq() {
      getOrglists({ iOrgnum: this.iOrgnum }).then(res => {
        // console.log(res)
        this.optionslist.push(res.data)
        // this.optionslist = res.data
      })
    },

    handleChange(val) {
      this.ruleForm.strOrgnum = 1
      // console.log(val)
    },
    handleSource() {
      this.visible = true
    },

    // 点击添加按钮时把数据清空
    addEquipment() {
      this.buttonadd = 1
      this.ruleForm.strAppname = ''
      this.ruleForm.strPackagename = ''
      this.ruleForm.strDetail = ''
      this.ruleForm.iApptype = ''
      this.ruleForm.strCover = ''
      this.ruleForm.id = ''
      this.strOrgnum = []
      this.strOrgnum.push(this.$store.getters.iOrgsysnum)
      this.dialogFormVisible = true
      // 新增dialog:title标题
      this.dialogStatus = 'addEquipment'
    },
    // 应用部署头部搜索
    handleSearch() {
      this.form.startTime = this.value[0]
      this.form.endTime = this.value[1]
      this.fetchList(this.form)
    },

    // 新增应用弹窗的确认按钮
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const arr = []
          this.strOrgnum.map(item => {
            arr.push(item)
          })
          // 此地方原来样子
          /* this.strOrgnum.map(item => {
                item.map(value => {
                  arr.push(value)
                })
              })*/
          // this.$ref.formName.clearFiles('strCover')
          this.addNoticewar([...new Set(arr)])
          this.dialogFormVisible = false
          // alert('submit!');
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 新增应用接口
    addNoticewar(arr) {
      this.ruleForm.strCover = this.mixUploadUrl
      this.ruleForm.valArr = arr
      addInfo(this.ruleForm)
        .then(res => {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.dialogFormVisible = false
          this.fetchList()
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 修改应用
    handelEdit(row, index) {
      this.buttonadd = 2
      this.ruleForm.strAppname = row.strAppname
      this.ruleForm.strPackagename = row.strPackagename
      this.ruleForm.iApptype = row.iApptype.toString()
      this.ruleForm.strDetail = row.strDetail
      this.ruleForm.iStatus = row.iStatus
      this.ruleForm.valArr = this.strOrgnum
      this.ruleForm.id = row.id
      this.ruleForm.iAppnum = row.iAppnum
      this.ruleForm.strCover = row.strCover
      this.ruleForm.strCoversize = row.strCoversize   //应用图片大小

      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'editEquipment'
      // (修改/详情)通过应用编号查询已经关联机构的应用信息
      detailrelevance({ iAppnum: row.iAppnum })
        .then(res => {
          this.fbVisibletable = true
          this.changefbDatas = res.refAppOrganList
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 点击应用类型清空链接和包名input
    clearinput() {
      this.ruleForm.strPackagename = ''
    },
    // 修改应用弹窗确认按钮
    changeFormbtn(formName) {
      // 这个地方之前有个参数row
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 回显多选框时候用的
          /* const arr = []
              this.strOrgnum.map(item => {
                item.map(value => {
                  arr.push(value)
                })
              })*/
          this.editNoticewar()
          // this.editNoticewar([...new Set(arr)])
          this.dialogFormVisible = false
          // alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 修改接口
    // editNoticewar(arr)
    editNoticewar() {
      // this.ruleForm.strCover = this.mixUploadUrl
      // this.ruleForm.valArr = arr
      updateAppInfo(this.ruleForm)
        .then(res => {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.dialogFormVisible = false
          this.fetchList()
          this.buttonadd = 1
        })
        .catch(err => {
          this.$message({
            type: 'success',
            message: '修改失败'
          })
          console.log(err)
        })
    },

    // 查看应用详情
    ShowDetail(row, index) {
      if (row.iApptype) {
        this.isVisible = parseInt(row.iApptype) === 1
      }
      detailTable({ iAppnum: row.iAppnum })
        .then(res => {
          this.gridData = []
          this.gridData.push(res.appInfo)
          this.gridDatas = res.ordInfoList
        })
        .catch(err => {
          console.log(err)
        })
      // 素材来源
      this.iAppnumTomat = row.iAppnum
      // (修改/详情)通过应用编号查询已经关联机构的应用信息
      detailrelevance({ iAppnum: row.iAppnum })
        .then(res => {
          // this.gridData.push(res.refAppOrganList)
          Object.assign(res.refAppOrganList, this.gridData) // 合并
          // res.refAppOrganList.map(item=>{this.gridData.push(item)})
        })
        .catch(err => {
          console.log(err)
        })
      fetchMaByApplist({ iAppnum: row.iAppnum })
        .then(res => {
          console.log('素材', res)
          this.materialDatas = res.ordInfoList
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 删除列表
    handleDelete(row, index) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteInfo({ iAppnum: row.iAppnum }).then(res => {
          this.$message({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.fetchList()
        })
      })
    },

    // 触发复选框（批量删除用）
    selsChange(val) {
      this.numArr = val
      console.log(val)
    },
    // 批量删除
    deleteFileOrDirectory() {
      const ids = []
      this.numArr.map(item => {
        ids.push(item.iAppnum)
      })
      this.numArr = ids
      console.log(this.numArr)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAllInfo({ numArr: ids }).then(res => {
            this.$message({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.numArr = ids
            this.fetchList()
          })
        })
        .catch(err => {
          console.error(err)
        })
    },

    // 列表分页序号排序
    indexMethod(index) {
      return index + 1 + (this.form.pagenum - 1) * this.limit
    },

    // 图片上传成功后
    handleSuccesslh(file, fileList) {
      // this.ruleForm.strCover = 1
    },
    beforeClose() {
      // 素材来源
      this.iAppnumTomat = ''
      this.dialogTableVisible = false
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style>
.myClass input.el-input__inner {
  color: #fff;
}

.myClass {
  display: none;
}

.el-image-viewer__close {
  color: #fff;
}
</style>
<style lang="scss" scoped>
.gridDataone {
  margin-top: 30px;
}
</style>
